import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controller/auth_controller.dart';

class AuthMiddleware extends GetMiddleware {
  @override
  int? get priority => 1;

  @override
  RouteSettings? redirect(String? route) {
    final authController = Get.find<AuthController>();
    
    // 需要登录的路由列表
    final protectedRoutes = ['/wallet', '/help'];
    
    // 如果访问受保护的路由且未登录，重定向到登录页面
    if (protectedRoutes.contains(route) && !authController.isLoggedIn.value) {
      // 显示登录对话框
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _showLoginRequiredDialog();
      });
      // 重定向到首页
      return RouteSettings(name: '/home');
    }
    
    return null;
  }
  
  void _showLoginRequiredDialog() {
    Get.dialog(
      AlertDialog(
        backgroundColor: Color(0xFF2A2A2A),
        title: Text(
          'login_required'.tr,
          style: TextStyle(color: Colors.white),
        ),
        content: Text(
          'login_required_message'.tr,
          style: TextStyle(color: Colors.grey[300]),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text(
              'cancel'.tr,
              style: TextStyle(color: Colors.grey[400]),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back();
              final authController = Get.find<AuthController>();
              authController.showLoginDialog();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
            ),
            child: Text(
              'login_button'.tr,
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }
}